﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CakeLibrary;
using Medianamik.Core;

namespace Medianamik.UI.Mediasend.Logic
{
    public class MediasendManager : Singleton<MediasendManager>
    {
        public string LastError { get; private set; }

        public MediasendManager()
        {
            //Todo : Ces infos ne devraient pas être hard codé!
            CakeGlobals.API_CAKE_URL = "http://api.cakemail.com";
            CakeGlobals.CAKE_INTERFACE_ID = 220;
            CakeGlobals.CAKE_INTERFACE_KEY = "3906a4a5950c56217feb581cf512e8b3";
            CakeGlobals.CAKE_MCRYPT_ALG = "blowfish";
            CakeGlobals.CAKE_MCRYPT_MODE = "ecb";
            CakeGlobals.CAKE_VERSION = "1.0";
            CakeGlobals.DEBUG = false;
            CakeGlobals.DEFAULT_LOCALE = "en_US";
            CakeGlobals.LOG_FILENAME = "debug.log";
            LastError = string.Empty;
        }

        public MediasendSession OpenSession(string username, string password)
        {
            try
            {
                if (username.IsNullOrEmpty() || password.IsNullOrEmpty())
                    return default(MediasendSession);

                var credentials = new Dictionary<string, object>()
                                      {
                                          {"email", username},
                                          {"password", password}
                                      };
                var userKey = CakeUser.Login(credentials)["user_key"].ToString();
                return new MediasendSession(userKey);
            }
            catch(CakeException ex)
            {
                LastError = ex.Message;
                return null;
            }
        }
    }
}
